package cn.ratel.route.interceptor;

import cn.ratel.aop.MethodInvocation;
import cn.ratel.component.Enhancers;
import cn.ratel.db.Page;
import cn.ratel.route.ContextHolder;
import cn.ratel.route.render.Tpl;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by iver
 */
public class PageInterceptor implements Enhancers.Enhancer {
	private String queryParamPath(Map<String, String[]> paramMap, StringBuilder sb) {
		paramMap.entrySet().stream().filter(param -> param.getValue() != null).forEach(param -> {
			for (String value : param.getValue()) {
				sb.append("&").append(param.getKey()).append("=").append(value);
			}
		});
		return sb.substring(1);
	}

	@Override
	public void enhance(MethodInvocation invocation) {
		invocation.invoke();
		Object returnValue = invocation.getReturnValue();
		if (returnValue instanceof Tpl) {
			Tpl tpl = (Tpl) returnValue;
			Map<String, Object> tplVariable = tpl.getVariable();

			if (tplVariable == null) {
				return;
			}
			Page page = null;
			for (Map.Entry<String, Object> entry : tplVariable.entrySet()) {
				if (entry.getValue() instanceof Page) {
					page = (Page) entry.getValue();
					break;
				}
			}

			if (page == null) {
				return;
			}
			Map<String, String[]> reqParamMap = ContextHolder.getParameterMap().get();
			tplVariable.put("_pageNumber", page.getPageNumber() + 1);
			tplVariable.put("_totalPage", page.getTotalPage());

			Map<String, String[]> paramMap = new HashMap<>();
			paramMap.putAll(reqParamMap);
			if (page.getPageNumber() < page.getTotalPage() - 1) {
				paramMap.put("p", new String[]{page.getPageNumber() + 1 + ""});
				tplVariable.put("_nextPageUrl", ContextHolder.getUri().get() + "?" + queryParamPath(paramMap, new StringBuilder()));
			}
			if (page.getPageNumber() > 0) {
				paramMap.put("p", new String[]{page.getPageNumber() - 1 + ""});
				tplVariable.put("_prevPageUrl", ContextHolder.getUri().get() + "?" + queryParamPath(paramMap, new StringBuilder()));
			}
		}
	}
}
